<?php
/**
 * 绑定银行卡类
 * Created by PhpStorm.
 * User: 王海东
 * Date: 2018/12/17
 * Time: 14:00
 */

namespace app\common\model;

use think\Db;

class Bankinfo
{
    private const TAB_NAME = 'bankinfo';
    private const TAB_USER = 'user';

    /**
     * 新增银行卡
     * @author 王海东
     * @date
     * @param int   $user_id 用户id
     * @param array $data
     *                       [
     *                       bankname            银行名称
     *                       bank_card_num       银行卡号
     *                       bank_branch         支行名称
     *                       busername           持卡人
     *                       card                身份证号
     *                       mobile              银行预留手机号
     *                       area                开户区
     *                       ]
     * @return bool
     * @throws \Exception
     */
    public function add(int $user_id, array $data)
    : bool {
        try {

            $insert = [
                'user_id'       => $user_id,
                'bankname'      => $data['bankname'] ?? '',
                'bank_card_num' => $data['bank_card_num'],
                'bank_branch'   => $data['bank_branch'] ?? '',
                'busername'     => $data['busername'],
                'card'          => $data['card'],
                'mobile'        => $data['mobile'],
                'area'          => $data['area'],
                'create_time'   => date('Y-m-d H:i:s'),
            ];

            $id = Db::name(self::TAB_NAME)
                    ->insertGetId($insert);
        } catch (\Exception $e) {
            throw new \Exception("银行卡添加失败");
        }

        return $id ? true : false;
    }

    /**
     * 检查是否存在
     * @author 王海东
     * @date
     * @param int    $type  1 id查询  2 银行卡号查询
     * @param string $value 要查询的值
     * @return bool
     * @throws \Exception
     */
    public function checkExits(int $type, string $value)
    : bool {

        if ($type === 1) {
            $field = "id";
        } elseif ($type === 2) {
            $field = "bank_card_num";
        } else {
            throw new \Exception("要检查的类型错误");
        }

        try {
            return Db::name(self::TAB_NAME)
                     ->field('id')
                     ->where($field, $value)
                     ->whereNull('delete_time')
                     ->find() ? true : false;
        } catch (\Exception $e) {
            throw new \Exception('查询错误');
        }
    }

    /**
     * 查询银行卡列表  (后台)
     * @author 王海东
     * @date
     * @param int   $admin_id 管理员id
     * @param array $map      检索条件
     *                        [
     *                        start_time  开始时间
     *                        end_time    截止时间
     *                        name        用户名或手机号
     *                        agent_name  代理商名称
     *                        ]
     * @param int   $page     页数
     * @param int   $pageSize 页幅
     * @return array
     * @throws \Exception
     */
    public function select(int $admin_id, array $map = [], int $page, int $pageSize)
    : array {

        $db = Db::name(self::TAB_NAME);

        $db->alias('b');
        $db->join(self::TAB_USER.' u', 'b.user_id = u.id', 'left');

        if (isset($map["start_time"])) {
            $db->where("b.create_time", ">= TIME", $map["start_time"]);
        }

        if (isset($map["end_time"])) {
            $db->where("b.create_time", "<= TIME", $map["end_time"]);
        }

        if (isset($map['name'])) {
            $db->where('u.name|u.tel', $map['name']);
        }

        $db->whereNull('b.delete_time');

        $a   = new Admin();
        $ids = $a->getIds($admin_id);

        if (isset($map['agent_name'])) {

            $agent = $a->getAdminByName($map['agent_name']);
            if ($agent) {
                $agent_id = $agent['id'];
                if (!in_array($agent_id, $ids)) {
                    $ids = 0;
                } else {
                    $ids = $a->getIds($agent_id);
                }
            } else {
                $ids = 0;
            }
        }

        $db->where('u.admin_id', 'in', $ids);

        //查询总数
        $count = $db->count("b.id");
        if ($count < 1) {
            return [
                "count" => 0,
                "list"  => [],
            ];
        }

        try {
            $data = $db->field([
                'b.id',
                'b.bankname',
                'b.bank_card_num',
                'b.bank_branch',
                'b.busername',
                'b.card',
                'b.mobile',
                'b.area',
                'b.create_time',
                'u.name',
                'u.tel',
                'u.admin_id',
            ])
                       ->order('b.create_time desc')
                       ->page($page, $pageSize)
                       ->select();

            $r = new Region();

            $a     = new Admin();
            $admin = $a->getAdmin();

            foreach ($data as $key => $val) {
                $region = $r->showSuperior($val['area']);

                $data[$key]['provice'] = $region[0]['name'] ?? '';
                $data[$key]['city']    = $region[1]['name'] ?? '';
                $data[$key]['area']    = $region[2]['name'] ?? '';

                $data[$key]['admin_name'] = $admin[$val['admin_id']]['name'];
            }

            return [
                "count" => $count,
                "list"  => $data,
            ];

        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 查询用户绑定的银行卡列表
     * @author 王海东
     * @date
     * @param int $user_id  用户id
     * @param int $page     页码
     * @param int $pageSize 页幅
     * @return array
     * @throws \Exception
     */
    public function userList(int $user_id, int $page, int $pageSize)
    : array {
        $db = Db::name(self::TAB_NAME);

        $db->alias('b');
        $db->join(self::TAB_USER.' u', 'b.user_id = u.id', 'left');

        if (isset($user_id)) {
            $db->where('b.user_id', $user_id);
        }

        $db->whereNull('b.delete_time');


        //查询总数
        $count = $db->count("b.id");
        if ($count < 1) {
            return [
                "count" => 0,
                "list"  => [],
            ];
        }

        try {
            $data = $db->field([
                'b.id',
                'b.bankname',
                'b.bank_card_num',
                'b.bank_branch',
                'b.busername',
                'b.card',
                'b.mobile',
                'b.area',
                'b.create_time',
                'u.name',
                'u.tel',
            ])
                       ->order('b.create_time desc')
                       ->page($page, $pageSize)
                       ->select();

            $r = new Region();

            foreach ($data as $key => $val) {
                $region = $r->showSuperior($val['area']);

                $data[$key]['provice'] = $region[0]['name'] ?? '';
                $data[$key]['city']    = $region[1]['name'] ?? '';
                $data[$key]['area']    = $region[2]['name'] ?? '';
            }

            return [
                "count" => $count,
                "list"  => $data,
            ];

        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 删除绑定的银行卡
     * @author 王海东
     * @date
     * @param int $id 银行卡id
     * @return bool
     * @throws \Exception
     */
    public function delete(int $id)
    : bool {
        try {
            return Db::name(self::TAB_NAME)
                     ->where('id', $id)
                     ->setField('delete_time', date('Y-m-d H:i:s')) ? true : false;
        } catch (\Exception $e) {
            throw new \Exception('删除失败');
        }
    }

    /**
     * 修改银行卡
     * @author 王海东
     * @date
     * @param int   $id 银行卡id
     * @param array $data
     *                  [
     *                  bankname            银行名称
     *                  bank_card_num       银行卡号
     *                  bank_branch         支行名称
     *                  busername           持卡人
     *                  card                身份证号
     *                  mobile              银行预留手机号
     *                  area                开户区
     *                  ]
     * @return bool
     * @throws \Exception
     */
    public function update(int $id, array $data)
    : bool {

        $update = [];
        if (isset($data["bankname"])) {
            $update["bankname"] = $data["bankname"];
        }
        if (isset($data["bank_card_num"])) {
            $update["bank_card_num"] = $data["bank_card_num"];
        }
        if (isset($data["bank_branch"])) {
            $update["bank_branch"] = $data["bank_branch"];
        }
        if (isset($data["busername"])) {
            $update["busername"] = $data["busername"];
        }
        if (isset($data["card"])) {
            $update["card"] = $data["card"];
        }
        if (isset($data["mobile"])) {
            $update["mobile"] = $data["mobile"];
        }
        if (isset($data["area"])) {
            $update["area"] = $data["area"];
        }

        try {

            return Db::name(self::TAB_NAME)
                     ->where('id', $id)
                     ->update($update) ? true : false;
        } catch (\Exception $e) {
            throw new \Exception('修改失败');
        }
    }

    /**
     * 查询银行卡详细信息
     * @author 王海东
     * @date
     * @param int $id 银行卡id
     * @return array
     * @throws \Exception
     */
    public function find(int $id)
    : array {

        try {
            $data = Db::name(self::TAB_NAME)
                      ->field([
                          'id',
                          'bankname',
                          'bank_card_num',
                          'bank_branch',
                          'busername',
                          'card',
                          'mobile',
                          'area',
                          'create_time',
                      ])
                      ->where('id', $id)
                      ->whereNull('delete_time')
                      ->find();

            if (!$data) {
                return [];
            }

            $r      = new Region();
            $region = $r->showSuperior($data['area']);

            $data['provice'] = $region[0]['name'] ?? '';
            $data['city']    = $region[1]['name'] ?? '';
            $data['area']    = $region[2]['name'] ?? '';

        } catch (\Exception $e) {
            throw new \Exception('查询失败');
        }

        return $data;
    }
}